package com.bw.interceptor;

import com.bw.common.JwtUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Cookie[] cookies = request.getCookies();
        boolean flag = false;
        if (cookies != null){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();

                if (name.equals("token")){
                    // 过滤出cookie里的 令牌token
                    String token  = cookie.getValue();

                     flag = JwtUtils.validToken(token);
                }
            }
        }

        if (flag == false){ // 令牌无效 跳转到登录页面
            response.sendRedirect("/loginPage.do");
            return false;
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
